<template>
  <el-upload
    style="display: inline-block; margin-right: 10px"
    :on-success="uploadSuccess"
    :file-list="fileList"
    action="/api/upload"
    multiple
    :show-file-list="showList"
    :limit="limit"
    :on-error="fileError"
    :on-remove="fileRemove"
    :headers="headers"
  >
    <el-button v-if="slotValue" type="primary" @click="handleClick">
      {{ name }}
      <i class="el-icon-upload el-icon--right"></i
    ></el-button>
  </el-upload>
</template>
<script setup>
import { ref, defineProps, defineEmits } from "vue";
import { Notification } from "element-ui";
import store from "@/store";

const emit = defineEmits(["changeFile"]);
const slotValue = ref(true);

const headers = {
  Authorization: store.state.token,
};
const props = defineProps({
  limit: {
    type: Number,
    default: () => 1,
  },
  showList: {
    type: Boolean,
    default: () => false,
  },
  name: {
    type: String,
    default: () => "新增",
  },
  fileList: {
    type: Array,
    default: () => [],
  },
});

//点击
const handleClick = () => {};
//文件上传
const uploadSuccess = (res) => {
  if (res.code == 0) {
    Notification({
      title: "成功",
      message: "上传成功",
      type: "success",
    });
    let [...temp] = props.fileList;
    temp.push({
      name: res.data[1],
      url: "api/" + res.data[0],
    });
    emit("changeFile", temp);
  } else {
    Notification({
      title: "失败",
      message: "上传失败",
      type: "warning",
    });
  }
  console.log("上传成功");
};
// 文件移除
const fileRemove = (file) => {
  console.dir(file);
  let [...temp] = props.fileList;
  temp.map((item, index) => {
    if (item.url == file.url) {
      temp.splice(index, 1);
    }
  });
  console.log(temp);
  emit("changeFile", temp);
};
//上传失败
const fileError = () => {
  Notification({
    title: "失败",
    message: "上传失败",
    type: "warning",
  });
};
console.log(props);
</script>
